package com.basic.ui.view.image.monitor

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target

/**
 *
 *
 */
class DebugMonitorStateRequestListener(val imageView: ImageView?) : RequestListener<Drawable> {
    override fun onLoadFailed(
        e: GlideException?,
        model: Any,
        target: Target<Drawable>,
        isFirstResource: Boolean
    ): Boolean {
        return false
    }

    override fun onResourceReady(
        resource: Drawable,
        model: Any,
        target: Target<Drawable>,
        dataSource: DataSource,
        isFirstResource: Boolean
    ): Boolean {
        val monitorModel = ImageMonitor.getMonitorResult(model)
        if (monitorModel != null) {
            val width = resource.intrinsicWidth
            val height = resource.intrinsicHeight
            val isOverFat = isOverLength(monitorModel.length, monitorModel.isGif)
            val isOverSize = width != 0 && height != 0 && isOverSize(
                monitorModel.width,
                monitorModel.height,
                width,
                height
            )
            if (imageView != null) {
                if (isNoClip(monitorModel.url)) {
                    imageView.setColorFilter(Color.parseColor("#B3FF0000"))
                } else if (isOverFat && isOverSize) {
                    imageView.setColorFilter(Color.parseColor("#B3FF0000"))
                } else if (isOverFat) {
                    imageView.setColorFilter(Color.parseColor("#B3FFFF00"))
                } else if (isOverSize) {
                    imageView.setColorFilter(Color.parseColor("#B30000FF"))
                } else {
                    imageView.colorFilter = null
                }
            }
        }
        return false
    }

    private fun isNoClip(url: String?): Boolean {
        return !url!!.contains("/w/") || !url.contains("/h/")
    }

    companion object {
        const val MAX_GIF = 2 * 1024 * 1024
        const val MAX_PIC = 100 * 1024

        private fun isOverLength(length: Long, isGif: Boolean): Boolean {
            return if (isGif) MAX_GIF < length else MAX_PIC < length
        }

        fun isOverSize(originWidth: Int, originHeight: Int, width: Int, height: Int): Boolean {
            return originHeight > 2 * height || originWidth > 2 * width
        }
    }
}